package net.j4love.dubbo.simulation.client;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @author He Peng
 * @create 2017-05-27 0:04
 * @update 2017-05-27 0:04
 * @updatedesc : 更新说明
 * @see
 */
public class ProxyInvoker {

    private final String address;
    private final Integer port;
    private final RpcInvocationHandler rpcInvocationHandler = new RpcInvocationHandler();

    public ProxyInvoker(String address ,Integer port) {
        this.address = address;
        this.port = port;
    }

    public <T> T getProxy(Class<T> tClass) {
        Class[] interfaces = new Class[]{tClass};
        T proxy = (T) Proxy.newProxyInstance(tClass.getClassLoader(),
                interfaces, rpcInvocationHandler);
        return proxy;
    }

    private class RpcInvocationHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            Socket socket = new Socket(ProxyInvoker.this.address,
                                        ProxyInvoker.this.port);

            PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
            String param = JSON.toJSONString(args[0]);

            out.println(param);

            InputStream inStream = socket.getInputStream();
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(inStream));
            String responseText = bufReader.readLine();
            return responseText;
        }
    }
}
